package org.example.controller;

import org.example.service.ShortUrlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 首页控制器
 * 用于直接访问短链接，如：http://localhost:8080/abc123
 * 
 * @author Your Name
 * @since 2024-07-01
 */
@Controller
public class HomeController {
    
    @Autowired
    private ShortUrlService shortUrlService;
    
    /**
     * 首页
     */
    @GetMapping("/")
    @ResponseBody
    public String home() {
        return """
            <!DOCTYPE html>
            <html>
            <head>
                <title>短链接服务</title>
                <meta charset="UTF-8">
                <style>
                    body { font-family: Arial, sans-serif; margin: 40px; }
                    .container { max-width: 800px; margin: 0 auto; }
                    .form-group { margin: 20px 0; }
                    label { display: block; margin-bottom: 5px; font-weight: bold; }
                    input[type="text"], input[type="number"] { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; }
                    button { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
                    button:hover { background: #0056b3; }
                    .result { margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 4px; }
                    .error { background: #f8d7da; color: #721c24; }
                    .success { background: #d4edda; color: #155724; }
                </style>
            </head>
            <body>
                <div class="container">
                    <h1>短链接服务</h1>
                    <p>输入长链接，生成短链接</p>
                    
                    <div class="form-group">
                        <label for="originalUrl">原始链接：</label>
                        <input type="text" id="originalUrl" placeholder="请输入要缩短的链接，如：https://www.example.com">
                    </div>
                    
                    <div class="form-group">
                        <label for="customCode">自定义编码（可选）：</label>
                        <input type="text" id="customCode" placeholder="8位自定义编码，如：my123">
                    </div>
                    
                    <div class="form-group">
                        <label for="expireDays">过期天数（可选）：</label>
                        <input type="number" id="expireDays" placeholder="链接过期天数，留空表示永不过期">
                    </div>
                    
                    <button onclick="createShortUrl()">生成短链接</button>
                    
                    <div id="result"></div>
                </div>
                
                <script>
                    async function createShortUrl() {
                        const originalUrl = document.getElementById('originalUrl').value;
                        const customCode = document.getElementById('customCode').value;
                        const expireDays = document.getElementById('expireDays').value;
                        
                        if (!originalUrl) {
                            showResult('请输入原始链接', false);
                            return;
                        }
                        
                        const request = {
                            originalUrl: originalUrl,
                            customCode: customCode || null,
                            expireDays: expireDays ? parseInt(expireDays) : null
                        };
                        
                        try {
                            const response = await fetch('/api/short-url/create', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify(request)
                            });
                            
                            const result = await response.json();
                            
                            if (result.code === 200) {
                                const data = result.data;
                                showResult(`
                                    <strong>短链接生成成功！</strong><br>
                                    短链接编码：${data.shortCode}<br>
                                    完整短链接：<a href="${data.shortUrl}" target="_blank">${data.shortUrl}</a><br>
                                    原始链接：${data.originalUrl}<br>
                                    过期时间：${data.expireTime || '永不过期'}
                                `, true);
                            } else {
                                showResult('生成失败：' + result.message, false);
                            }
                        } catch (error) {
                            showResult('请求失败：' + error.message, false);
                        }
                    }
                    
                    function showResult(message, isSuccess) {
                        const resultDiv = document.getElementById('result');
                        resultDiv.innerHTML = message;
                        resultDiv.className = 'result ' + (isSuccess ? 'success' : 'error');
                    }
                </script>
            </body>
            </html>
            """;
    }
    
    /**
     * 直接访问短链接
     * 如：http://localhost:8080/abc123
     */
    @GetMapping("/{shortCode}")
    public void redirectToOriginalUrl(
            @PathVariable String shortCode,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        
        String ipAddress = getClientIpAddress(request);
        String userAgent = request.getHeader("User-Agent");
        String referer = request.getHeader("Referer");
        
        String originalUrl = shortUrlService.redirectToOriginalUrl(shortCode, ipAddress, userAgent, referer);
        
        if (originalUrl != null) {
            response.sendRedirect(originalUrl);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("""
                <!DOCTYPE html>
                <html>
                <head>
                    <title>短链接不存在</title>
                    <meta charset="UTF-8">
                    <style>
                        body { font-family: Arial, sans-serif; text-align: center; margin-top: 100px; }
                        .error { color: #721c24; background: #f8d7da; padding: 20px; border-radius: 5px; display: inline-block; }
                    </style>
                </head>
                <body>
                    <div class="error">
                        <h2>短链接不存在或已过期</h2>
                        <p>短链接编码：<strong>%s</strong></p>
                        <p><a href="/">返回首页</a></p>
                    </div>
                </body>
                </html>
                """.formatted(shortCode));
        }
    }
    
    /**
     * 获取客户端真实IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}
